package num;

import java.math.BigInteger;
import java.util.Arrays;

/**
 * @program: data_structures_algorithms
 * @description: 大整数之和
 * @author: lld
 * @create: 2021-04-12 20:36
 **/
public class BigNumSum {
    public static void main(String[] args) {
//        直接使用BigInteger
        BigInteger bigInteger = new BigInteger("9999899999");
        BigInteger bigInteger1 = new BigInteger("1111111111");
        System.out.println(bigInteger.add(bigInteger1));

        String s = bigNumSum("1111111111", "9999899999");
        System.out.println(s);
    }

    public static String bigNumSum(String s1, String s2) {
//        取最长的整数位数
        int maxLength = Math.max(s1.length(), s2.length()) + 1;

        int[] num1 = new int[maxLength];
        for (int i = 0; i < s1.length(); i++) {
//            - '0' 将char转int
            num1[i] = s1.charAt(s1.length() - i - 1) - '0';
        }
        int[] num2 = new int[maxLength];
        for (int i = 0; i < s2.length(); i++) {
            num2[i] = s2.charAt(s2.length() - i - 1) - '0';
        }

        int[] sumArr = new int[maxLength];
        int temp = 0;
        for (int i = 0; i < maxLength; i++) {
            temp += num1[i];
            temp += num2[i];
            if (temp >= 10) {
                sumArr[i] = temp % 10;
                temp = 1;
            } else {
                sumArr[i] = temp;
                temp = 0;
            }
        }
//        数组倒序输出，第一位有0去掉
        StringBuilder sb = new StringBuilder();
        if (sumArr[maxLength - 1] == 0) {
            for (int i = maxLength - 2; i >= 0; i--) {
                sb.append(sumArr[i]);
            }
        } else {
            for (int i = maxLength - 1; i >= 0; i--) {
                sb.append(sumArr[i]);
            }
        }
        return sb.toString();
    }
}
